package com.x_memteor.base_master.application;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDex;
import android.widget.Toast;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.interfaces.BetaPatchListener;
import com.tencent.bugly.crashreport.CrashReport;
import com.vise.xsnow.common.GsonUtil;
import com.vise.xsnow.http.ViseHttp;
import com.x_memteor.base_master.bean.GameBean;
import com.x_memteor.base_master.bean.LogEvent;
import com.x_memteor.base_master.bean.ScorBean;
import com.x_memteor.base_master.bean.response.NewHeartBean;
import com.x_memteor.base_master.bean.response.TokenBean;
import com.x_memteor.base_master.bean.response.UpWeightBean;
import com.x_memteor.base_master.constants.Constants;
import com.x_memteor.base_master.utils.GsonUtils;
import com.x_memteor.base_master.utils.LogUtils;
import com.x_memteor.base_master.utils.SharedPreferencesUtils;
import com.x_memteor.base_master.utils.converter.aesConverterFactory.AesConverterFactory;
import com.x_memteor.base_master.utils.converter.jsonConverterFactory.JsonConverterFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.tencent.bugly.beta.tinker.TinkerManager.getApplication;


/**
 * @author: Meteor
 * @description: 自定义的Application类
 * @version:
 * @date: 2016/12/28 0028 15:50
 * @company:
 * @email: lx802315@163.com
 */
public class MyApplication extends Application {

    //定义一个标记
    private static String TAG;

    //当前的用户
//    private static UserInfo currentUser;

    //用于存放倒计时时间
    public static Map<String, Long> map;

    /**
     * 维护一个全局的context对象
     */
    public Context context;

    //用于存放数据
    private static Map<String, Object> datas = new HashMap<>();
    //单例模式
    private static MyApplication myApplication;

    public List<ScorBean> getScorBeanList() {
        if (scorBeanList == null) {
            scorBeanList = new ArrayList<>();
        }
        return scorBeanList;
    }

    public void setScorBeanList(List<ScorBean> scorBeanList) {
        this.scorBeanList = scorBeanList;
    }

    List<ScorBean> scorBeanList;

    public static MyApplication getInstance() {
        return myApplication;
    }

    public TokenBean mTokenBean;

    public GameBean getGameBean() {
        if (gameBean == null) {
            gameBean = new GameBean();
        }
        return gameBean;
    }

    public void setGameBean(GameBean gameBean) {
        this.gameBean = gameBean;
    }

    private GameBean gameBean;

    public void saveGameBean(String gameName) {
        if (gameBean != null) {
            SharedPreferencesUtils.putString(this, gameName, GsonUtils.getInstance().toJson(gameBean));
        }
    }

    public GameBean getGameBean(String gameName) {
        Gson gson = new Gson();
        gameBean = gson.fromJson(SharedPreferencesUtils.getString(this, gameName, ""), GameBean.class);
        return gameBean;
    }

    /**
     * 获取当前的用户对象
     *
     * @return
     */
    public TokenBean getCurrentUser() {
        TokenBean user = mTokenBean;
        if (user != null) {
            return user;
        }
        return new TokenBean();
    }

    public void setCurrentUser(TokenBean currentUser) {
        this.mTokenBean = currentUser;
    }

    public int getMic() {
        if (getCurrentUser() != null) {
            return getCurrentUser().getMacid();
        } else {
            return 0;
        }
    }

    public String getToken() {
        if (getCurrentUser() != null) {
            return getCurrentUser().getToken();
        } else {
            return "";
        }
    }

    public long getExpires() {
        if (getCurrentUser() != null) {
            return getCurrentUser().getExpires();
        } else {
            return 0;
        }
    }

    public static Object getDatas(String key, boolean delFlag) {
        if (delFlag) {
            return datas.remove(key);
        }
        return datas.get(key);
    }

    public static Object putDatas(String key, Object value) {
        return datas.put(key, value);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TAG = this.getClass().getSimpleName();
        //初始化Logger打印类，定义全局TAG
        Logger.init("X_Meteor").logLevel(LogLevel.FULL);
        //由于Application类本身已经单例，所以直接按以下处理即可。
        myApplication = this;
        context = getApplicationContext();

        setHotFixListener();

        initHttp();

        //初始化热修复
        Bugly.init(this, "9e4c469920", true);
        //初始化bugly s：appId
        CrashReport.initCrashReport(getApplicationContext(), "9e4c469920", true);

    }

    private void initHttp() {
        ViseHttp.init(this);
        ViseHttp.CONFIG()
                //配置请求主机地址
                .baseUrl(Constants.BASE_URL_DEV)
                //配置全局请求头
                .globalHeaders(new HashMap<String, String>())
                //配置全局请求参数
                .globalParams(new HashMap<String, String>())
                //配置应用级拦截器
                .interceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        LogUtils.print("X_Meteor", message);
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BODY))
                .converterFactory(AesConverterFactory.create())
                .converterFactory(GsonConverterFactory.create())
                .converterFactory(JsonConverterFactory.create())
                //添加CallAdapter工厂
                .callAdapterFactory(RxJava2CallAdapterFactory.create())
                //配置读取超时时间，单位秒
                .readTimeout(30)
                //配置写入超时时间，单位秒
                .writeTimeout(30)
                //配置连接超时时间，单位秒
                .connectTimeout(30)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000);
    }

    private Gson buildGson() {
        return new GsonBuilder()
                .serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
//                // 此处可以添加Gson 自定义TypeAdapter
//                .registerTypeAdapter(UserInfo.class, new UserInfoTypeAdapter())
                .create();
    }

    private void setHotFixListener() {
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFile) {
//                Toast.makeText(getApplication(), "补丁下载地址" + patchFile, Toast.LENGTH_SHORT).show();
                LogUtils.print("CrashReport", "补丁下载地址" + patchFile);
            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
//                Toast.makeText(getApplication(),
//                        String.format(Locale.getDefault(), "%s %d%%",
//                                Beta.strNotificationDownloading,
//                                (int) (totalLength == 0 ? 0 : savedLength * 100 / totalLength)),
//                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadSuccess(String msg) {
//                Toast.makeText(getApplication(), "补丁下载成功", Toast.LENGTH_SHORT).show();
                LogUtils.print("CrashReport", "补丁下载成功");
            }

            @Override
            public void onDownloadFailure(String msg) {
//                Toast.makeText(getApplication(), "补丁下载失败", Toast.LENGTH_SHORT).show();
                LogUtils.print("CrashReport", "补丁下载失败");

            }

            @Override
            public void onApplySuccess(String msg) {
//                LogUtils.print("CrashReport", "补丁应用成功,重启应用");
//                Toast.makeText(getApplication(), "补丁应用成功,重启应用", Toast.LENGTH_SHORT).show();
                restartApplication();
            }

            @Override
            public void onApplyFailure(String msg) {
//                Toast.makeText(getApplication(), "补丁应用失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPatchRollback() {
//                Toast.makeText(getApplication(), "补丁回滚", Toast.LENGTH_SHORT).show();
            }
        };
    }

    //重启应用
    private void restartApplication() {
//        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);

        Intent mStartActivity = getPackageManager().getLaunchIntentForPackage(getPackageName());
        int mPendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // 安装tinker
        Beta.installTinker();
    }
}
